Save search results to database
- Under
db.mysql
package, create class/MySQLConnection.java
. - Implement
DBConnection
interface - Implement both
close
method andconstructor
.
1 | // connection |
- implement
searchItems()
inMySQLConnection
. Previously we callTicketMasterAPI.search
from ourSearchItem
servlet directly. But actually our recommendation code also needs to call the same search function, so we make a designated function here to do the search call.
The code is simply copied from what we’ve already had inSearchItem.java
.
1 | /** |
- after
searchItem
, let’s trysaveItem
to save data into database. Again, careful with the import suggestions. Always choosejava.sql.*
.
1 | /** |
Use PreparedStatement and stmt.settring() can effectively avoid SQL injection.
PreparedStatement is faster than raw String. Only have to create it once.
- SQL injection. Turns the input to the SQL statement, and makes the query always true.
1 |
|
- update
DBConnectionFactory
.
1 | public static DBConnection getConnection(String db) { |
- In
src/rpc/SearchItem.java
, add a privatedbconnection
field and updatedoGet()
.
1 | /** |
Implement set/unset favorite related functions
- let’s try setFavoriteItem and unsetFavoriteItem
1 | /** |
create a new servlet called
ItemHistory
, update the url mapping to\history
create a new function in RpcHelper.java to parse HTTP request body. Imagine the input HTTP request looks like:
1 | { |
1 | /** |
- update
doPost()
anddoDelete
inItemHistory.java
to use this new function.
1 | /** |
- open postman, switch to
post
method, use http://localhost:8080/Jupiter/history, then copy the following JSON object into body. Replaceitem_id1
anditem_id2
with the realitem_id
exist in your item table.
1 | { |
- now let’s send another request to test our delete function. Open another tab in postman, switch method to
delete
, use http://localhost:8080/Jupiter/history, then copy the following JSON object into body. Again replaceitem_id1
with the realitem_id
exist in your history table.1
2
3
4
5
6{
'user_id':'1111',
'favorite' : [
'item_id1',
]
}